$:.unshift(File.join(File.dirname(__FILE__), '..'))

require 'sitemap_spider/sitemap'
require 'sitemap_spider/sitemap_record'
include SitemapSpider

namespace :sitemap_spider do

  def docstr(docopts)
    defopts = Sitemap.default_opts
    docstr = ''
    docopts.each {|o| docstr << sprintf(" %s=%s", o.to_s.upcase, defopts[o])}
    return docstr
  end

  docopts = [:host, :port, :protocol, :start_path, :add_only_valid,
    :check_max_url_length, :max_url_length, :output_file, :output_tmp_file,
    :debug, :report_a_reference, :errors_are_fatal, :sleep_between_requests,
    :process_order_is_fifo, :print_totals, :produce_sitemap, :lock_file]
  desc "Crawles a site and generates sitemap.xml file in public directory. Options with defaults:" + docstr(docopts) +
       ". HOST and PROTOCOL must be in lowercase, DEBUG prints errors and warnings to stderr. If the " +
       "process receives a HUP signal, it will print status of work to stdout."
  task :sitemap_from_site do
    initial_config
    @sm = Sitemap.new(@opts)
    @sm.sitemap_from_site
  end

  docopts = [:output_file, :output_tmp_file, :input_file, :add_only_valid,
    :debug, :errors_are_fatal, :sleep_between_requests, :print_totals, :produce_sitemap, :lock_file]
  desc "Generates sitemap.xml from links given in a file. Options with defaults:" + docstr(docopts) + '.'
  task :sitemap_from_links do
    initial_config
    @sm = Sitemap.new(@opts)
    @sm.sitemap_from_links
  end

  desc "Generates sitemap.xml from yaml array of hashes given in a file. Options with defaults:" + docstr(docopts) + '.'
  task :sitemap_from_yaml do
    initial_config
    @sm = Sitemap.new(@opts)
    @sm.sitemap_from_yaml
  end

  def initial_config
    @opts = {}
    # boolean opts
    Sitemap.boolean_opts.each do |key, value|
      @opts.merge!(key => (ENV[key.to_s.upcase] ? ENV[key.to_s.upcase] == 'true' : value))
    end
    # numeric opts
    Sitemap.numeric_opts.each do |key, value|
      @opts.merge!(key => (ENV[key.to_s.upcase] ? ENV[key.to_s.upcase].to_i : value))
    end
    # string opts
    Sitemap.string_opts.each do |key, value|
      @opts.merge!(key => (ENV[key.to_s.upcase] ? ENV[key.to_s.upcase] : value))
    end

    trap("HUP") {@sm.inspect_state; @sm.inspect_state(true)}
  end
end
